import React, { useState, useEffect } from 'react';
import {
  Button,
  Space,
  Tag,
  Modal,
  Form,
  message,
  Dropdown,
  Typography,
  Tooltip,
  Popconfirm
} from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  EyeOutlined,
  MoreOutlined,
  UserOutlined,
  RobotOutlined,
  SettingOutlined,
  ClearOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { MenuProps } from 'antd';
import dayjs from 'dayjs';
import * as aiChatService from '@/services/aiChat';
import type { 
  AiChatRecord, 
  AiChatQueryParams,
  AiChatApiResponse
} from '@/types';
import { SearchForm, DataTable } from '@/components';
import type { SearchFieldConfig, PaginationConfig, ToolbarAction, BatchAction } from '@/components';

const { Text, Paragraph } = Typography;

// 消息类型配置
const MESSAGE_TYPES = {
  user: { color: 'blue', text: '用户', icon: <UserOutlined /> },
  assistant: { color: 'green', text: 'AI助手', icon: <RobotOutlined /> },
  system: { color: 'orange', text: '系统', icon: <SettingOutlined /> }
};

const AiChatPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [records, setRecords] = useState<AiChatRecord[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState<PaginationConfig>({
    current: 1,
    pageSize: 20,
    total: 0,
  });

  // 搜索相关
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<AiChatQueryParams>({});

  // 模态框状态
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [sessionModalVisible, setSessionModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<AiChatRecord | null>(null);
  const [sessionRecords, setSessionRecords] = useState<AiChatRecord[]>([]);

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = [
    {
      name: 'keyword',
      type: 'input',
      placeholder: '搜索消息内容',
      width: 200,
      prefix: <SearchOutlined />
    },
    {
      name: 'user_id',
      type: 'input',
      placeholder: '用户ID',
      width: 120
    },
    {
      name: 'session_id',
      type: 'input',
      placeholder: '会话ID',
      width: 200
    },
    {
      name: 'message_type',
      type: 'select',
      placeholder: '选择消息类型',
      width: 120,
      options: [
        { label: '用户', value: 'user' },
        { label: 'AI助手', value: 'assistant' },
        { label: '系统', value: 'system' }
      ]
    },
    {
      name: 'dateRange',
      type: 'dateRange',
      placeholder: '创建时间'
    }
  ];

  // 获取AI对话记录列表
  const fetchRecords = async (params: AiChatQueryParams = {}) => {
    setLoading(true);
    try {
      const queryParams = {
        page: pagination.current,
        limit: pagination.pageSize,
        ...searchParams,
        ...params,
      };

      const response: AiChatApiResponse<AiChatRecord> = await aiChatService.getAiChatList(queryParams);
      if (response.success && response.data) {
        setRecords(response.data.records || []);
        setPagination(prev => ({
          ...prev,
          current: response.data.pagination?.page || 1,
          total: response.data.pagination?.total || 0,
        }));
      }
    } catch (error: any) {
      message.error(error?.message || '获取AI对话记录失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化
  useEffect(() => {
    fetchRecords();
  }, []);

  // 搜索
  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    const params: AiChatQueryParams = {
      page: 1,
      limit: pagination.pageSize,
    };

    if (values.keyword) params.keyword = values.keyword;
    if (values.user_id) params.user_id = Number(values.user_id);
    if (values.session_id) params.session_id = values.session_id;
    if (values.message_type) params.message_type = values.message_type;
    if (values.dateRange && values.dateRange.length === 2) {
      params.start_date = values.dateRange[0].format('YYYY-MM-DD');
      params.end_date = values.dateRange[1].format('YYYY-MM-DD');
    }

    setSearchParams(params);
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchRecords(params);
  };

  // 重置搜索
  const handleResetSearch = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchRecords({ page: 1, limit: pagination.pageSize });
  };

  // 分页变化
  const handlePaginationChange = (page: number, pageSize?: number) => {
    setPagination(prev => ({ ...prev, current: page, pageSize: pageSize || 20 }));
    fetchRecords({ ...searchParams, page, limit: pageSize || 20 });
  };

  // 查看详情
  const handleViewDetail = (record: AiChatRecord) => {
    setCurrentRecord(record);
    setDetailModalVisible(true);
  };

  // 查看会话
  const handleViewSession = async (sessionId: string) => {
    try {
      setLoading(true);
      const records = await aiChatService.getSessionChatRecords(sessionId);
      setSessionRecords(records);
      setSessionModalVisible(true);
    } catch (error: any) {
      message.error(error?.message || '获取会话记录失败');
    } finally {
      setLoading(false);
    }
  };

  // 删除记录
  const handleDelete = async (record: AiChatRecord) => {
    try {
      await aiChatService.deleteAiChatRecord(record.id);
      message.success('删除成功');
      fetchRecords();
    } catch (error: any) {
      message.error(error?.message || '删除失败');
    }
  };

  // 删除会话
  const handleDeleteSession = async (sessionId: string) => {
    try {
      const result = await aiChatService.deleteSessionChatRecords(sessionId);
      message.success(`删除成功，影响${result.deletedCount}条记录`);
      fetchRecords();
    } catch (error: any) {
      message.error(error?.message || '删除会话失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的记录');
      return;
    }

    try {
      const result = await aiChatService.batchDeleteAiChatRecords(selectedRowKeys as number[]);
      message.success(`批量删除成功，影响${result.deletedCount}条记录`);
      setSelectedRowKeys([]);
      fetchRecords();
    } catch (error: any) {
      message.error(error?.message || '批量删除失败');
    }
  };

  // 清理过期记录
  const handleCleanupExpired = async () => {
    Modal.confirm({
      title: '清理过期记录',
      content: '确定要清理30天前的记录吗？此操作不可恢复。',
      onOk: async () => {
        try {
          const result = await aiChatService.cleanupExpiredChatRecords(30);
          message.success(`清理完成，删除了${result.deletedCount}条记录`);
          fetchRecords();
        } catch (error: any) {
          message.error(error?.message || '清理失败');
        }
      }
    });
  };

  // 表格列配置
  const columns: ColumnsType<AiChatRecord> = [
    {
      title: '用户信息',
      key: 'userInfo',
      width: 150,
      render: (_, record) => (
        <div>
          <div className="font-medium">
            {record.username || `用户${record.user_id}`}
          </div>
          <div className="text-gray-500 text-sm">
            ID: {record.user_id}
          </div>
        </div>
      ),
    },
    {
      title: '会话ID',
      dataIndex: 'session_id',
      key: 'session_id',
      width: 200,
      render: (sessionId) => (
        <Tooltip title="点击查看完整会话">
          <Button 
            type="link" 
            size="small"
            onClick={() => handleViewSession(sessionId)}
          >
            {sessionId ? `${sessionId.substring(0, 8)}...` : '-'}
          </Button>
        </Tooltip>
      ),
    },
    {
      title: '消息类型',
      dataIndex: 'message_type',
      key: 'message_type',
      width: 100,
      render: (type: 'user' | 'assistant' | 'system') => (
        <Tag color={MESSAGE_TYPES[type]?.color} icon={MESSAGE_TYPES[type]?.icon}>
          {MESSAGE_TYPES[type]?.text}
        </Tag>
      ),
    },
    {
      title: '消息内容',
      dataIndex: 'content',
      key: 'content',
      render: (content) => (
        <Paragraph 
          ellipsis={{ rows: 2, expandable: true }}
          style={{ marginBottom: 0, maxWidth: '300px' }}
        >
          {content}
        </Paragraph>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => {
        const items: MenuProps['items'] = [
          {
            key: 'view',
            icon: <EyeOutlined />,
            label: '查看详情',
            onClick: () => handleViewDetail(record),
          },
          {
            key: 'session',
            icon: <EyeOutlined />,
            label: '查看会话',
            onClick: () => handleViewSession(record.session_id),
          },
          {
            type: 'divider',
          },
          {
            key: 'delete',
            icon: <DeleteOutlined />,
            label: '删除',
            danger: true,
            onClick: () => {
              Modal.confirm({
                title: '确认删除',
                content: '确定要删除这条记录吗？',
                onOk: () => handleDelete(record),
              });
            },
          },
          {
            key: 'deleteSession',
            icon: <DeleteOutlined />,
            label: '删除整个会话',
            danger: true,
            onClick: () => {
              Modal.confirm({
                title: '确认删除会话',
                content: `确定要删除会话 "${record.session_id}" 的所有记录吗？`,
                onOk: () => handleDeleteSession(record.session_id),
              });
            },
          },
        ];

        return (
          <Dropdown menu={{ items }} placement="bottomRight">
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        );
      },
    },
  ];

  // 工具栏动作配置
  const toolbarActions: ToolbarAction[] = [
    {
      key: 'cleanup',
      label: '清理过期记录',
      icon: <ClearOutlined />,
      onClick: handleCleanupExpired
    }
  ];

  // 批量操作配置
  const batchActions: BatchAction[] = [
    {
      key: 'delete',
      label: '批量删除',
      icon: <DeleteOutlined />,
      danger: true,
      onClick: () => {
        Modal.confirm({
          title: '确认批量删除',
          content: `确定要删除所选的 ${selectedRowKeys.length} 条记录吗？`,
          onOk: handleBatchDelete,
        });
      },
    },
  ];

  return (
    <div className="space-y-6">
      {/* 搜索区域 */}
      <SearchForm
        fields={searchFields}
        form={searchForm}
        onSearch={handleSearch}
        onReset={handleResetSearch}
        loading={loading}
      />

      {/* AI对话记录列表 */}
      <DataTable<AiChatRecord>
        title="AI对话记录"
        columns={columns}
        dataSource={records}
        rowKey="id"
        loading={loading}
        pagination={{
          ...pagination,
          onChange: handlePaginationChange,
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        toolbarActions={toolbarActions}
        batchActions={batchActions}
        adaptiveHeight={true}
        scroll={{ x: 1200 }}
      />

      {/* 详情模态框 */}
      <Modal
        title="AI对话记录详情"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setCurrentRecord(null);
        }}
        footer={null}
        width={600}
      >
        {currentRecord && (
          <div className="space-y-4">
            <div>
              <Text strong>用户：</Text>
              <Text>{currentRecord.username || `用户${currentRecord.user_id}`}</Text>
            </div>
            <div>
              <Text strong>会话ID：</Text>
              <Text code>{currentRecord.session_id}</Text>
            </div>
            <div>
              <Text strong>消息类型：</Text>
              <Tag color={MESSAGE_TYPES[currentRecord.message_type]?.color}>
                {MESSAGE_TYPES[currentRecord.message_type]?.text}
              </Tag>
            </div>
            <div>
              <Text strong>创建时间：</Text>
              <Text>{dayjs(currentRecord.created_at).format('YYYY-MM-DD HH:mm:ss')}</Text>
            </div>
            <div>
              <Text strong>消息内容：</Text>
              <div className="mt-2 p-3 bg-gray-50 rounded">
                <Paragraph style={{ marginBottom: 0 }}>
                  {currentRecord.content}
                </Paragraph>
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* 会话记录模态框 */}
      <Modal
        title="会话记录"
        open={sessionModalVisible}
        onCancel={() => {
          setSessionModalVisible(false);
          setSessionRecords([]);
        }}
        footer={null}
        width={800}
      >
        <div className="max-h-96 overflow-y-auto space-y-3">
          {sessionRecords.map((record) => (
            <div 
              key={record.id} 
              className={`p-3 rounded ${
                record.message_type === 'user' 
                  ? 'bg-blue-50 ml-8' 
                  : record.message_type === 'assistant'
                  ? 'bg-green-50 mr-8'
                  : 'bg-gray-50'
              }`}
            >
              <div className="flex justify-between items-center mb-2">
                <Tag color={MESSAGE_TYPES[record.message_type]?.color} icon={MESSAGE_TYPES[record.message_type]?.icon}>
                  {MESSAGE_TYPES[record.message_type]?.text}
                </Tag>
                <Text type="secondary" className="text-xs">
                  {dayjs(record.created_at).format('HH:mm:ss')}
                </Text>
              </div>
              <div>{record.content}</div>
            </div>
          ))}
        </div>
      </Modal>
    </div>
  );
};

export default AiChatPage; 